<?php
class Core_Model_DbTable_Posts extends Core_Model_DbTable_Base_Action {
    protected $_name = "posts";
    protected $_id_social_name = 'id_social_post';
    
    public function getDetail($id_socials) {
        $facebook_wraper = new MKT_Facebook_Wraper();
        $params = 'fields=from,to,picture,message,created_time';
        $post_details = $facebook_wraper->getBatchData($id_socials, $params);
        $refined_data = array();
        foreach ($post_details as $post_detail) {
            if (!$this->isAdminAction($post_detail)) { //admin exception
                $refined_data[] = $this->refinePostDetail($post_detail);    
            }
        }
        return $refined_data;
    }
    
    public function refinePostDetail($post_detail) {
        $result = array();
        foreach ($post_detail as $field => $value) {
            $col = $field;
            $data = $value;
            switch ($field) {
                case 'from': 
                    $data = $value['id'];
                    $result['from_name'] = $value['name'];
                    $result['target_id_social_from'] = $data;
                    break;
                case 'created_time':
                    $data = strtotime($value);
                    $result['target_created_time'] = $data;
                    break;
                case 'id':
                    $col = 'id_social_post';
                    break;
            }
            $result[$col] = $data;
        }
        $to = Core_Util::getIdPage($result['id_social_post']);
        $result['to'] = $to;
        return $result;
    }
    
    public function insertBatchData($array_data) {
        if (empty($array_data)) {
            return;
        }
        $cols = $this->getCols();
        $str_cols = $this->colsToStr($cols);
        $sql = "INSERT IGNORE INTO {$this->_name} ($str_cols) VALUES ";
        foreach ($array_data as $data) {
            $prepared_data = array();
            foreach ($cols as $col) {
                if (!isset($data[$col])) {
                    $prepared_data[] = NULL;
                } else {
                    $prepared_data[] = $data[$col];
                }
            }
            $val  = $this->getAdapter()->quoteInto("(?),", $prepared_data);
            $sql .= $val;
        }
        $final_sql = rtrim($sql, ",");
        $this->getAdapter()->query($final_sql);
    }
    
    protected function getCols() {
        return array (
            'id_social_post', 'from'    , 'to',
            'picture'       , 'message' , 'link', 'source',
            'caption'       , 'type'    , 'description', 'created_time'
        );
    }
    
    protected function isAdminAction($post) {
        return (!isset($post['to'])) || ($post['from'] == $post['to']);
    }
}
?>
